
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import watermark from './utils/watermark.js'

NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/ddLogin', '/wxLogin', '/register', '/aiibLogin', '/auth-redirect', '/bind', '/register', '/flybookLogin', '/recoverpw', '/SysShareHome', '/indicatorLogin', '/license']

router.onError(error => {
  if (error.code === 'MODULE_NOT_FOUND') {
    router.push({ path: '/error/404', query: { name: Cookies.get('_no-name_'), id: Cookies.get('_no-id_') }})
  }
})

// var dialog = false

// import { setCurrentRunningApp } from 'qiankun/es/sandbox/common'
router.beforeEach((to, from, next) => {
  // setCurrentRunningApp(null)
  var productName = localStorage.getItem('productName') || 'J博士'
  // console.log(productName)
  var item = store.getters.route_list.find(info => info.path === to.fullPath)
  if (item) {
    var name = window.i18n.t(item.children[0].name)
    var title = ''
    if (!(productName === undefined || productName === null || productName === '' || productName === ' ')) {
      title = window.i18n.t(productName) + '-'
    }
    document.title = title + name
  } else {
    if (to.name) {
      const title = window.i18n.t(to.name)
      var nameTile = ''
      if (!(productName === undefined || productName === null || productName === '' || productName === ' ')) {
        nameTile = window.i18n.t(productName) + '-'
      }
      document.title = nameTile + title
    }
  }
  // NProgress.start()
  if (getToken()) {
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else if (to.path === '/flybookLogin') {
      next({ path: '/' })
      NProgress.done()
    } else if (to.path === '/ddLogin') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(res => {
          // 拉取user_info
          if (res !== undefined && res.code === 200) {
            const roles = res.roles
            // console.log(res.datas.user)
            var user = res.datas.user
            watermark.set(user.nickName, user.email, user.phonenumber)
            store.dispatch('app/getComponentsLayout')
            store.dispatch('app/getShowEn')
            store.dispatch('app/getShowIm')
            store.dispatch('app/getDefaultPageSize')
            store.dispatch('app/getMenuLayout')
            store.dispatch('app/getFilePoteUser')
            store.dispatch('getSelTreeUser')
            store.dispatch('getDept')
            store.commit('app/SET_CHAT_URL')
            store.dispatch('getMediationList')
            store.dispatch('getMediationTeamList')
            store.dispatch('marketApp/SET_HAS_WEEKLY_APP')
            store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
              // 测试 默认静态页面
              // store.dispatch('permission/generateRoutes', { roles }).then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              // console.log(accessRoutes)
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
              // console.log(store)
              var permission_routes_visible = store.getters.permission_routes.filter((item) => !item.hidden && item.parentId === '0')
              var navActive = store.getters.navActive

              if (to.meta.notPass) {
                next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
              } else if (to.path === '/act/task/processingTask') {
                // 如果是待办路径走这里
                next({ ...to, replace: true })
              } else if (!navActive) {
                if (permission_routes_visible.length > 0) {
                  store.dispatch('genLeftList', permission_routes_visible[0])
                  next({ path: permission_routes_visible[0].redirect })
                }
              } else {
                next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
              }

              store.dispatch('getLoginPasswordStatus').then(res => {
                if (res.msg !== '0' && to.path !== '/resetPassword') {
                  next({ path: '/resetPassword' })
                  NProgress.done()
                } else if (res.msg === '0' && to.path === '/resetPassword') {
                  next({ path: '/' })
                } else {
                  next()
                  NProgress.done()
                }
              })
            })
          } else {
            store.dispatch('FedLogOut').then(() => {
              next({ path: '/' })
            })
          }
        })
          .catch(err => {
            store.dispatch('FedLogOut').then(() => {
              Message.error(err)
              next({ path: '/' })
            })
          })
      } else {
        store.dispatch('getLoginPasswordStatus').then(res => {
          if (res.msg !== '0' && to.path !== '/resetPassword') {
            // dialog = true
            // 如果没修改过密码，跳转修改密码页面
            // MessageBox.confirm(window.i18n.t(res.msg === '1' ? '系统检测，当前密码为初始化密码，请修改密码' : '系统检测，密码已超过三个月未修改，请修改密码'), window.i18n.t('提示'), {
            //   showCancelButton: false,
            //   showClose: false,
            //   confirmButtonText: window.i18n.t('前往修改'),
            //   closeOnClickModal: false
            // }).then(() => {
            //   dialog = false
            //   next({ path: '/resetPassword' })
            //   NProgress.done()
            // })
            next({ path: '/resetPassword' })
            NProgress.done()
          } else {
            next()
            NProgress.done()
          }
        })
        // next()
        // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
        // if (hasPermission(store.getters.roles, to.meta.roles)) {
        //   next()
        // } else {
        //   next({ path: '/401', replace: true, query: { noGoBack: true }})
        // }
        // 可删 ↑
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // 如果通过aiib.smyun.net 访问则跳转到亚投行登录页
      const splitElement = window.location.host.split('.')[0]
      if (splitElement === 'dhxt') {
        next(`/aiibLogin`)
      } else {
        next(`/login`)
      }
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

